package com.heima.search.filter;

import com.alibaba.fastjson.JSON;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.threadlocal.ApUserThreadLocalUtils;
import lombok.extern.log4j.Log4j2;
import org.springframework.core.annotation.Order;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@Log4j2
@WebFilter(filterName = "behaviorTokenFilter",urlPatterns = "/*")
@Order(1)
public class BehaviorTokenFilter extends GenericFilterBean {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request=  (HttpServletRequest)servletRequest;

        //获取请求头中的userId
        String user = request.getHeader("user");

        if (user!=null&&user.length()>0){
            ApUser apUser = JSON.parseObject(user, ApUser.class);
            //存入到本地线程变量
            ApUserThreadLocalUtils.setUser(apUser);
        }

        filterChain.doFilter(servletRequest,servletResponse);

    }
}
